"""
数据分析
"""
import os
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import jieba

from config import LOCALHOST
from app.db.db import db_query_keywords

WC_MASK_IMG = 'D:\\studyProject\\python\\blog\\app\\static\\images\\analysis\\mould.jpg'  # 作为词云的轮廓图片
KEYWORDS_FILE_PATH = '/keyword.txt'  # 存放关键字的txt文件


def storage_word():
    """
    从数据查询关键字数据存到keyword.txt
    :return:
    """
    res = db_query_keywords(num=0)
    if os.path.exists(KEYWORDS_FILE_PATH):
        os.remove(KEYWORDS_FILE_PATH)
    with open(KEYWORDS_FILE_PATH, 'a+') as file:
        for item in res:
            file.write('\n'.join(item))


def cut_word():
    with open(KEYWORDS_FILE_PATH) as file:
        keyword_txt = file.read()
        wordList = jieba.cut(keyword_txt, cut_all=True)
        wl = " ".join(wordList)
        print(wl)
        return wl


def create_word_cloud():
    """
    生成词云
    :return:
    """
    # 设置词云形状
    storage_word()
    wc_mask = np.array(Image.open(WC_MASK_IMG))
    # 清除无用的词语
    # 设置词云的配置，如大小等
    wc = WordCloud(font_path="simhei.ttf", background_color="white", max_words=50, mask=wc_mask, max_font_size=50,
                   random_state=42)
    wc.generate(cut_word())
    plt.imshow(wc, interpolation="bilinear")
    plt.axis("off")
    plt.figure()
    plt.show()
    wc.to_file("D:\\studyProject\\python\\blog\\app\\static\\images\\analysis\\wct.jpg")
    url = 'http://'+LOCALHOST+':5002/static/images/analysis/wct.jpg'
    return url
